package com.zHan.aop;

import com.alibaba.fastjson.JSONObject;
import com.zHan.mapper.OperateLogMapper;
import com.zHan.pojo.OperateLog;
import com.zHan.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;


@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.zHan.anno.Log)")
    private void pt(){}

    @Around("pt()")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //准备参数
        //获得token
        String jwt = request.getHeader("token");
        //解析成json
        Claims claims = JwtUtils.parseJWT(jwt);
        //获得操作人id
        Integer operateUser = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        //操作开始时间
        long begin = System.currentTimeMillis();
        //操作方法返回值
        Object result = joinPoint.proceed();
        //操作结束时间
        long end = System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        long costTime = end - begin;

        //封装对象
        OperateLog operateLog=new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);

        //执行操作
        operateLogMapper.insert(operateLog);

        log.info("AOP记录操作日志: {}" , operateLog);
        return result;
    }
}
